<?php

namespace App\Events;

use App\Models\Agent;
use App\Models\AgentWebsiteLetter;
use App\Models\WebsiteLetter;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;

class AgentLogin extends Event
{
    private $agentId;

    public function __construct($agentId)
    {
        $this->agentId = $agentId;
    }

    public function handle()
    {
        try {
            \Cache::lock('RECEIVE_LETTER_FROM_AGENTS_STATION_' . $this->agentId, 10)
                ->block(3, function () {
                    try {
                        \DB::transaction(function () {
                            // 接收站内信
                            // 找到获取的最后一封所有人站内信 ID
                            $theLastWebsiteLetter = AgentWebsiteLetter::query()
                                ->where([
                                    'agent_id' => $this->agentId,
                                    'website_letter_range_type' => AgentWebsiteLetter::RANGE_TYPE_ALL
                                ])
                                ->orderByDesc('id')
                                ->first(['website_letter_id']);// 如果有最后一封, 就按照最后一封的 ID 开始找
                            $now = Carbon::now()->format('Y-m-d H:i:s');
                            AgentWebsiteLetter::query()->insert(
                                WebsiteLetter::query()
                                    ->where([
                                        'range_type' => WebsiteLetter::RANGE_TYPE_ALL,
                                    ])
                                    ->when($theLastWebsiteLetter, function (Builder $builder, $theLastWebsiteLetter) {
                                        $builder->where('id', '>', $theLastWebsiteLetter['website_letter_id']);
                                    })
                                    ->get()
                                    ->reverse()
                                    ->map(function ($letter) use ($now) {
                                        return [
                                            'agent_id' => $this->agentId,
                                            'website_letter_id' => $letter['id'],
                                            'website_letter_range_type' => AgentWebsiteLetter::RANGE_TYPE_ALL,
                                            'created_at' => $now,
                                            'updated_at' => $now,

                                        ];
                                    })
                                    ->toArray()
                            );
                        });
                    } catch (\Exception $e) {
                        \Log::error('接收站内信发生错误: ' . $e->getMessage());
                    }
                });

            Agent::query()->find($this->agentId)->increment('login_frequency', 1, ['last_time_of_login' => Carbon::now()]); // 登录次数加一, 最后一次登录时间
        } catch (\Exception $e) {
            \Log::warning('获取"接收站内信"锁发生错误' . $e->getMessage());
        }
    }
}
